<template>
  <div class="ingredient-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>配料信息</span>
        </div>
      </template>

      <!-- 操作栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增
          </el-button>
          <el-select 
            v-model="selectedDatabase" 
            placeholder="请选择数据库"
            style="width: 200px; margin-left: 10px;"
            @change="handleDatabaseChange"
          >
            <el-option
              v-for="db in databaseList"
              :key="db.id"
              :label="db.name"
              :value="db.id"
            />
          </el-select>
        </div>
        <div class="toolbar-right">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入货号/国际条码/品名"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button 
            type="success" 
            @click="handleExport" 
            :disabled="tableData.length === 0"
            plain
          >
            <el-icon><Download /></el-icon>
            导出Excel
          </el-button>
        </div>
      </div>

      <!-- 列表信息 -->
      <div class="list-container">
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          v-loading="loading"
          :height="tableHeight"
        >
          <el-table-column type="index" label="序号" width="60" align="center" fixed />
          <el-table-column prop="itemNo" label="货号" width="150" fixed />
          <el-table-column prop="barcode" label="国际条码" width="150" />
          <el-table-column prop="itemName" label="品名" width="200" show-overflow-tooltip />
          <el-table-column prop="material" label="配料表" width="300" show-overflow-tooltip />
          <el-table-column prop="standard" label="执行标准" width="150" show-overflow-tooltip />
          <el-table-column prop="weight" label="净含量" width="120" />
          <el-table-column prop="condition" label="存储条件" width="150" show-overflow-tooltip />
          <el-table-column prop="processWay" label="加工方式" width="120" />
          <el-table-column prop="manufacturer" label="生产商" width="180" show-overflow-tooltip />
          <el-table-column prop="origin" label="生产产地" width="150" />
          <el-table-column prop="attr3" label="属性3" width="120" />
          <el-table-column prop="attr4" label="属性4" width="120" />
          <el-table-column prop="attr5" label="属性5" width="120" />
          <el-table-column prop="attr6" label="属性6" width="120" />
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 汇总栏 -->
        <div class="summary-bar">
          <span class="summary-label">总数量：</span>
          <span class="summary-value"><strong>{{ totalCount }}</strong></span>
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货号" prop="itemNo">
              <el-input 
                v-model="formData.itemNo" 
                :disabled="isEdit" 
                placeholder="请输入货号"
                @blur="handleItemNoBlur"
                @keyup.enter="handleItemNoBlur"
                :loading="checkingItemNo"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国际条码">
              <el-input v-model="formData.barcode" disabled placeholder="自动带出" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="品名" prop="itemName">
          <el-input v-model="formData.itemName" disabled placeholder="自动带出" />
        </el-form-item>
        <el-form-item label="配料表">
          <el-input 
            v-model="formData.material" 
            type="textarea" 
            :rows="3"
            placeholder="请输入配料表"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行标准">
              <el-input v-model="formData.standard" placeholder="请输入执行标准" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="净含量">
              <el-input v-model="formData.weight" placeholder="请输入净含量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存储条件">
              <el-input v-model="formData.condition" placeholder="请输入存储条件" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加工方式">
              <el-input v-model="formData.processWay" placeholder="请输入加工方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产商">
              <el-input v-model="formData.manufacturer" placeholder="请输入生产商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产产地">
              <el-input v-model="formData.origin" placeholder="请输入生产产地" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="属性3">
              <el-input v-model="formData.attr3" placeholder="请输入属性3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性4">
              <el-input v-model="formData.attr4" placeholder="请输入属性4" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="属性5">
              <el-input v-model="formData.attr5" placeholder="请输入属性5" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属性6">
              <el-input v-model="formData.attr6" placeholder="请输入属性6" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleSave">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Plus, Download } from '@element-plus/icons-vue'
import { getDatabaseList } from '@/api/database'
import { API_BASE_URL } from '@/config/api'
import * as XLSX from 'xlsx'

interface DatabaseItem {
  id: number
  name: string
}

interface IngredientItem {
  itemNo: string
  barcode: string
  itemName: string
  material: string
  standard: string
  weight: string
  condition: string
  processWay: string
  manufacturer: string
  origin: string
  attr3: string
  attr4: string
  attr5: string
  attr6: string
}

const loading = ref(false)
const saveLoading = ref(false)
const checkingItemNo = ref(false)
const tableHeight = ref(500)
const searchKeyword = ref('')
const selectedDatabase = ref<number | null>(null)
const databaseList = ref<DatabaseItem[]>([])
const tableData = ref<IngredientItem[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增配料')
const isEdit = ref(false)
const isExistingItem = ref(false) // 标记是否已存在（需要更新）
const formRef = ref<FormInstance>()

const formData = reactive<IngredientItem>({
  itemNo: '',
  barcode: '',
  itemName: '',
  material: '',
  standard: '',
  weight: '',
  condition: '',
  processWay: '',
  manufacturer: '',
  origin: '',
  attr3: '',
  attr4: '',
  attr5: '',
  attr6: ''
})

const rules: FormRules = {
  itemNo: [{ required: true, message: '请输入货号', trigger: 'blur' }],
  itemName: [{ required: true, message: '请输入品名', trigger: 'blur' }]
}

// 计算总数量
const totalCount = computed(() => tableData.value.length)

// 加载数据库列表
const loadDatabaseList = async () => {
  try {
    const res = await getDatabaseList()
    if (res.success && res.data) {
      databaseList.value = res.data
      // 默认选择第一个数据库
      if (databaseList.value.length > 0) {
        selectedDatabase.value = databaseList.value[0].id
      }
    }
  } catch (error) {
    console.error('加载数据库列表失败:', error)
  }
}

// 数据库切换
const handleDatabaseChange = () => {
  // 清空表格数据
  tableData.value = []
}

// 搜索查询
const handleSearch = async () => {
  if (!selectedDatabase.value) {
    ElMessage.warning('请选择数据库')
    return
  }

  loading.value = true
  
  try {
    // 调用后端API
      const response = await fetch(`${API_BASE_URL}/api/basic/ingredient-list`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        databaseId: selectedDatabase.value,
        keyword: searchKeyword.value || ''
      })
    })

    const result = await response.json()
    
    if (result.success) {
      tableData.value = result.data || []
      ElMessage.success(`查询成功，共 ${tableData.value.length} 条配料信息`)
    } else {
      ElMessage.error(result.message || '查询失败')
      tableData.value = []
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请检查网络连接')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.itemNo = ''
  formData.barcode = ''
  formData.itemName = ''
  formData.material = ''
  formData.standard = ''
  formData.weight = ''
  formData.condition = ''
  formData.processWay = ''
  formData.manufacturer = ''
  formData.origin = ''
  formData.attr3 = ''
  formData.attr4 = ''
  formData.attr5 = ''
  formData.attr6 = ''
  formRef.value?.clearValidate()
}

// 新增
const handleAdd = () => {
  if (!selectedDatabase.value) {
    ElMessage.warning('请先选择数据库')
    return
  }
  isEdit.value = false
  isExistingItem.value = false
  dialogTitle.value = '新增配料'
  resetForm()
  dialogVisible.value = true
}

// 货号输入完成后检查
const handleItemNoBlur = async () => {
  if (!formData.itemNo || !selectedDatabase.value || isEdit.value) {
    return
  }

  const itemNo = formData.itemNo.trim()
  if (!itemNo) {
    return
  }

  checkingItemNo.value = true

  try {
    const response = await fetch(`${API_BASE_URL}/api/basic/ingredient-check`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        databaseId: selectedDatabase.value,
        itemNo: itemNo
      })
    })

    const result = await response.json()

    if (result.success) {
      const data = result.data
      
      if (data.existsInProperty) {
        // 配料表中已存在
        ElMessage.warning('配料表已存在，点击保存将执行更新操作')
        isExistingItem.value = true
        dialogTitle.value = '更新配料（已存在）'
        
        // 带出所有信息（包括更新货号字段）
        formData.itemNo = data.itemNo || ''
        formData.barcode = data.barcode || ''
        formData.itemName = data.itemName || ''
        formData.material = data.material || ''
        formData.standard = data.standard || ''
        formData.weight = data.weight || ''
        formData.condition = data.condition || ''
        formData.processWay = data.processWay || ''
        formData.manufacturer = data.manufacturer || ''
        formData.origin = data.origin || ''
        formData.attr3 = data.attr3 || ''
        formData.attr4 = data.attr4 || ''
        formData.attr5 = data.attr5 || ''
        formData.attr6 = data.attr6 || ''
      } else if (data.existsInItem) {
        // 商品信息表中存在，可以新增
        ElMessage.success('商品信息匹配成功，请填写配料信息')
        isExistingItem.value = false
        dialogTitle.value = '新增配料'
        
        // 带出基本信息（包括更新货号字段）
        formData.itemNo = data.itemNo || ''
        formData.barcode = data.barcode || ''
        formData.itemName = data.itemName || ''
      } else {
        // 商品信息不存在
        ElMessage.error('商品信息不存在，请检查货号')
        formData.itemNo = ''
        formData.barcode = ''
        formData.itemName = ''
      }
    } else {
      ElMessage.error(result.message || '查询失败')
    }
  } catch (error) {
    console.error('检查货号失败:', error)
    ElMessage.error('检查货号失败，请检查网络连接')
  } finally {
    checkingItemNo.value = false
  }
}

// 编辑
const handleEdit = (row: IngredientItem) => {
  if (!selectedDatabase.value) {
    ElMessage.warning('请先选择数据库')
    return
  }
  isEdit.value = true
  dialogTitle.value = '编辑配料'
  
  formData.itemNo = row.itemNo
  formData.barcode = row.barcode
  formData.itemName = row.itemName
  formData.material = row.material
  formData.standard = row.standard
  formData.weight = row.weight
  formData.condition = row.condition
  formData.processWay = row.processWay
  formData.manufacturer = row.manufacturer
  formData.origin = row.origin
  formData.attr3 = row.attr3
  formData.attr4 = row.attr4
  formData.attr5 = row.attr5
  formData.attr6 = row.attr6
  
  dialogVisible.value = true
}

// 保存
const handleSave = async () => {
  if (!formRef.value || !selectedDatabase.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        let url = ''
        let operationType = ''
        
        if (isEdit.value) {
          // 编辑模式：更新
          url = `${API_BASE_URL}/api/basic/ingredient-update`
          operationType = '修改'
        } else if (isExistingItem.value) {
          // 新增模式但配料已存在：更新
          url = `${API_BASE_URL}/api/basic/ingredient-update`
          operationType = '更新'
        } else {
          // 新增模式且配料不存在：插入
          url = `${API_BASE_URL}/api/basic/ingredient-add`
          operationType = '新增'
        }
        
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            databaseId: selectedDatabase.value,
            ...formData
          })
        })

        const result = await response.json()
        
        if (result.success) {
          ElMessage.success(`${operationType}成功`)
          dialogVisible.value = false
          handleSearch()
        } else {
          ElMessage.error(result.message || '操作失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('操作失败，请检查网络连接')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 删除
const handleDelete = (row: IngredientItem) => {
  if (!selectedDatabase.value) {
    ElMessage.warning('请先选择数据库')
    return
  }
  
  ElMessageBox.confirm(`确定要删除配料"${row.itemName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/basic/ingredient-delete`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          databaseId: selectedDatabase.value,
          itemNo: row.itemNo
        })
      })

      const result = await response.json()
      
      if (result.success) {
        ElMessage.success('删除成功')
        handleSearch()
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }).catch(() => {})
}

// 导出Excel
const handleExport = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  try {
    // 准备导出数据
    const exportData = tableData.value.map((item, index) => ({
      '序号': index + 1,
      '货号': item.itemNo,
      '国际条码': item.barcode,
      '品名': item.itemName,
      '配料表': item.material,
      '执行标准': item.standard,
      '净含量': item.weight,
      '存储条件': item.condition,
      '加工方式': item.processWay,
      '生产商': item.manufacturer,
      '生产产地': item.origin,
      '属性3': item.attr3,
      '属性4': item.attr4,
      '属性5': item.attr5,
      '属性6': item.attr6
    }))

    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 6 },   // 序号
      { wch: 15 },  // 货号
      { wch: 18 },  // 国际条码
      { wch: 25 },  // 品名
      { wch: 40 },  // 配料表
      { wch: 20 },  // 执行标准
      { wch: 12 },  // 净含量
      { wch: 20 },  // 存储条件
      { wch: 15 },  // 加工方式
      { wch: 25 },  // 生产商
      { wch: 18 },  // 生产产地
      { wch: 12 },  // 属性3
      { wch: 12 },  // 属性4
      { wch: 12 },  // 属性5
      { wch: 12 }   // 属性6
    ]
    worksheet['!cols'] = colWidths

    // 创建工作簿
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '配料信息')

    // 生成文件名（带时间戳）
    const now = new Date()
    const fileName = `配料信息_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}.xlsx`

    // 导出文件
    XLSX.writeFile(workbook, fileName)

    ElMessage.success(`成功导出 ${tableData.value.length} 条配料数据`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

onMounted(() => {
  loadDatabaseList()
  tableHeight.value = window.innerHeight - 360
})
</script>

<style scoped>
.ingredient-container {
  width: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.list-container {
  margin-top: 20px;
}

.summary-bar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 16px;
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

.summary-value {
  font-size: 16px;
  color: #303133;
}

.summary-value strong {
  color: #409eff;
  font-size: 20px;
}
</style>
